#include "volumeslider.h"
#include <QDebug>
#include <QFocusEvent>
#include <QTimer>
//#include <QString>
//extern "C"
//{

#include <string.h>
#include <math.h>
#include <stdlib.h>
#include <stdio.h>

#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <sys/ioctl.h>
#include <sys/soundcard.h>
//}
VolumeSlider::VolumeSlider(QWidget *parent)
    :QSlider(Qt::Vertical,parent)
{
    this->setRange(0,100);
    this->setMaximum(100);
    this->setMinimum(0);
    this->setValue(get_volume());

    connect(this,SIGNAL(valueChanged(int)),this,SLOT(setVolume(int)));
}
VolumeSlider::~VolumeSlider()
{
}

/*
*   func usage: if the mousebutton left setVolume called
*       and then execute to set the volume
*/
void VolumeSlider::setVolume(int value)
{
    //int fd;
    //   int inc;

    /*fd=*/open_mixer();
    this->set_volume(value);
    //qDebug()<<"Set Right";


}
/*
*   func usage: open "/dev/mixer"
*
*/
int VolumeSlider::open_mixer()
{
    int fd;
    fd=::open("/dev/mixer",O_WRONLY);
    // fd=::open("/dev/mixer",O_RDWR);
    if(fd < 0)
    {
        fprintf(stderr, "Error opening %s: %s\n","/dev/mixer", strerror(errno));
        return -1;
    }
    return fd;
}

/*
*   func usage: get the current volume
*
*/
int VolumeSlider::get_volume()
{
    int fd,data;

    fd=open_mixer();
    if(fd<0)
    {
        return -1;
    }

    if(::ioctl(fd,MIXER_READ(SOUND_MIXER_VOLUME), &data) == -1)


    {
        //if(::ioctl(fd,SOUND_MIXER_VOLUME, &data) == -1) {
        //printf("无法打开指定声卡\n");


        qDebug()<<"can not open sound card get volume\n";
        close_mixer(fd);
        return -1;
    }

    return data;
}

/*
*   func usage: set volume
*
*/
int VolumeSlider::set_volume(int data)
{
    int fd;
    int i;
    //  int lvol,rvol;
    fd=open_mixer();
    if(fd<0)
    {
        return -1;
    }

    if(data < 0 || data > 100)
    {
        close_mixer(fd);
        qDebug()<<"data you input has error";
        return 0;
    }

    data=(data<<8)|data; //Here important.
    /*
 if (::ioctl(fd, MIXER_WRITE(SOUND_MIXER_VOLUME), &data) == -1)

  {

        qDebug("can't open the soundcard set volume\n");
        close_mixer(fd);
        return 0;
    }
    */

    for(i=0;i<SOUND_MIXER_NRDEVICES;i++)  //Here important.
    {
        ::ioctl(fd,MIXER_WRITE(i),&data);

    }
    //qDebug(QString::number(data));
    close_mixer(fd);
    return 1;
}
void VolumeSlider::close_mixer(int fd)
{
    ::close(fd);
}
void VolumeSlider::focusOutEvent(QFocusEvent *)
{
    emit focusOut();
}
void VolumeSlider::focusInEvent(QFocusEvent *)
{
    emit focusIn();
}


